<template>
  <div v-loading="loading">
    <div class="title-gra authorityDiv">
      <span style="color:#0090ff">用户资源目录权限</span>
      <span class="right">
        <i :class="mlflag ? 'el-icon-arrow-down' : 'el-icon-arrow-up'" @click="mlflagOpen"></i>
      </span>
      <!-- <div class="grab gra-r"></div> -->
    </div>
    <div v-show="mlflag" id="mlflag">
      <el-tree
        :props="defaultProps"
        :data="treeData"
        node-key="resourceId"
        ref="tree"
        show-checkbox
        @check="handleCheckChange"
        @node-expand="handleNodeClick"
        @current-change="handelCurrentChange"
        :class="view ? 'viewcheckbox' : ''"
      ></el-tree>
      <!-- :load="loadNode" -->
      <div class="mt-20 mr-btn">
        <el-button v-if="!view && treeData.length!=0" type="primary" @click="saveZYMLQX">确定</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import {
  dataauthorityAuthority,
  getDataArea,
  getUserResourceByLevel,
  getDataAreaTable,
  getAreaTableTB,
  saveResourceAuthority,
  getResourceAuthority
} from "@/api/authority.js";
// import { LEV1, LEV2, LEV3 } from "./data.js";
import { deteleObject } from "@/filters/index.js";
export default {
  name: "TabDataType",
  data() {
    return {
      mlflag: true,
      treeData: [],
      defaultProps: {
        children: "children",
        label: "resourceName"
      },
      checkedIdArr: [],
      loading: false,
      defaultCheck: [],
      checkedDataList: []
    };
  },
  props: ["view", "roleId"],
  methods: {
    handleNodeClick(val1, val2, val3) {
      console.log("节点展开的情况", val1, val2, val3);
    },
    handleCheckChange(val1, val2, val3) {
      console.log("复选框选择的情况", val1, val2, val3);
      val1.checked = !val1.checked;
    },
    handelCurrentChange(val1, val2, val3) {
      console.log("节点选择的情况", val1, val2, val3);
    },
    mlflagOpen() {
      this.mlflag = !this.mlflag;
    },
    //获取库区 获取已勾选的权限
    async getDataAreaAll(node, resolve) {
      this.loading = true;
      this.treeData = [];
      this.checkedIdArr = [];
      this.formateTree();
      await getResourceAuthority(this.roleId).then(res => {
        let dataList = res.data;
        //  console.log(dataList,`所有选中`);
        for (let i = 0; i < dataList.length; i++) {
          if (dataList[i]["resourceLevel"] == "3") {
            this.checkedIdArr.push(dataList[i]["resourceId"]);
          }
        }
      });
      // console.log(this.checkedIdArr,`过滤部分`);
      this.$nextTick(() => {
        this.$refs.tree.setCheckedKeys(this.checkedIdArr);
        this.loading = false;
      });
    },
    //获取一级、二级、三级数据
    async formateTree() {
      let lev1 = await getUserResourceByLevel({ level: "01" }),
        lev1Data;
      lev1Data = lev1.data;
      let lev2 = await getUserResourceByLevel({ level: "02" }),
        lev2Data;
      lev2Data = lev2.data;
      let lev3 = await getUserResourceByLevel({ level: "03" }),
        lev3Data;
      lev3Data = lev3.data;

      let childOf2 = {}; //{"id":[,,,]}
      for (let i = 0, resourceId2; i < lev3Data.length; i++) {
        resourceId2 = lev3Data[i]["parent"];
        if (!childOf2[resourceId2]) {
          childOf2[resourceId2] = [];
        }
        childOf2[resourceId2].push(lev3Data[i]);
      }
      // console.log(childOf2);
      let childOf1 = {};
      for (let k = 0, resourceId1; k < lev2Data.length; k++) {
        lev2Data[k]["children"] = childOf2[lev2Data[k]["resourceId"]] || [];
        resourceId1 = lev2Data[k]["parent"];
        if (!childOf1[resourceId1]) {
          childOf1[resourceId1] = [];
        }
        childOf1[resourceId1].push(lev2Data[k]);
      }
      //  console.log(childOf1);
      for (let j = 0; j < lev1Data.length; j++) {
        lev1Data[j]["children"] = childOf1[lev1Data[j]["resourceId"]] || [];
      }
      // console.log(lev1Data);
      this.treeData = lev1Data;
    },
    // async formateTree(){
    //   let lev1=await getDataArea({id:"",level:"01"}),lev1Data;
    //   lev1Data=lev1.data;// level: "01",resourceId: 19,resourceName: "originald"
    //   for(let i=0,lev2,lev2Data,lev3,lev3Data;i<lev1Data.length;i++){
    //       lev2=await getDataArea({id:lev1Data[i]['resourceId'],level:"02"});
    //       lev2Data=lev2.data;
    //       if(lev2Data.length){//二级存在,查找三级
    //         for(let k=0;k<lev2Data.length;k++){
    //             lev3=await getDataArea({id:lev2Data[k]['resourceId'],level:"03"});
    //             lev3Data=lev3.data;
    //             lev2Data[k]["children"]=[...lev3Data];
    //         }
    //         lev1Data[i]['children']=[...lev2Data];
    //       }else{
    //         lev1Data[i]['children']=[];
    //       }
    //   }
    //   this.treeData = lev1Data;
    //   this.$refs.tree.setCheckedKeys(this.checkedIdArr);
    //   this.loading = false;
    // },
    saveZYMLQX() {
      let seletData = this.$refs.tree.getCheckedNodes();
      let halfSelectData = this.$refs.tree.getHalfCheckedNodes();
      // console.log(this.checkedIdArr);
      // console.log(seletData, halfSelectData);
      //组装后台需要的数据
      let data = [];
      seletData.forEach(res => {
        let map = {
          level: res.level,
          parentId: res.parent,
          resourceId: res.resourceId,
          resourceName: res.resourceName,
          flag: 1
        };
        data.push(map);
        if (res.parentValue) {
          let map = {
            level: res.parentValue.level,
            parentId: res.parentValue.parent,
            resourceId: res.parentValue.resourceId,
            resourceName: res.parentValue.resourceName,
            flag: res.parentValue.checked ? 1 : 0
          };
          data.push(map);
          if (res.parentValue) {
            let map = {
              level: res.parentValue.level,
              parentId: res.parentValue.parent,
              resourceId: res.parentValue.resourceId,
              resourceName: res.parentValue.resourceName,
              flag: res.parentValue.checked ? 1 : 0
            };
            data.push(map);
          }
        }
      });
      halfSelectData.forEach(res => {
        let map = {
          level: res.level,
          parentId: res.parent,
          resourceId: res.resourceId,
          resourceName: res.resourceName,
          flag: 0
        };
        data.push(map);
      });
      data = deteleObject(data);
      for (let k = 0; k < data.length; k++) {
        if (data[k]["level"] == "01") {
          data[k]["parentId"] = data[k]["resourceId"];
        }
      }
      const params = {
        roleId: this.roleId,
        data: data
      };
      // console.log("wqwqwqwqwqwqwqqw===处理后的结构", data);
      saveResourceAuthority(params).then(res => {
        if (res.success) {
          this.$message.success("保存用户资源目录权限成功");
        } else {
          this.$message.error(res.message);
        }
      });
    }
  }
};
</script>
<style scoped>
#mlflag > div {
  width: 100%;
}
</style>
